package com.macro.mall.portal.util;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class Test {

    private static final String appId = "wx59d87a41d72f796b";
    //唯一标识

    //深房金融 AppSecret
    private static final String appSecret = "e9590210a539cbc5bc620031b5254592";

    public static JSONObject getAccessToken() throws Exception {
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        String requestUrl = accessTokenUrl.replace("APPID", appId).replace("APPSECRET", appSecret);
//        log.info("getAccessToken.requestUrl====>"+requestUrl);
//        JSONObject result = HttpUtil.doGet(requestUrl);
        JSONObject jsonObject = MyHttpUtil.sendJsonGET(requestUrl);
        String token = jsonObject.getString("access_token");
        int expiresIn = jsonObject.getInt("expires_in");
        ConcurrentHashMapCacheUtils.setCache("access_token",token,expiresIn * 1000L);
        return jsonObject;
    }

    public static JSONObject getJsApiTicket(String accessToken) throws Exception {
        String apiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        String requestUrl = apiTicketUrl.replace("ACCESS_TOKEN", accessToken);
//        log.info("getJsApiTicket.requestUrl====>"+requestUrl);
        JSONObject result = MyHttpUtil.sendJsonGET(requestUrl);

        return result;
    }

    //生成微信权限验证的参数
    public static Map<String, String> makeWXTicket(String jsApiTicket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonceStr = createNonceStr();
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsApiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
//        log.info("String1=====>"+string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
//            log.info("signature=====>"+signature);
        } catch (NoSuchAlgorithmException e) {
//            log.error("WeChatController.makeWXTicket=====Start");
//            log.error(e.getMessage(),e);
//            log.error("WeChatController.makeWXTicket=====End");
        } catch (UnsupportedEncodingException e) {
//            log.error("WeChatController.makeWXTicket=====Start");
//            log.error(e.getMessage(),e);
//            log.error("WeChatController.makeWXTicket=====End");
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsApiTicket);
        ret.put("nonceStr", nonceStr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", appId);

        return ret;
    }

    //字节数组转换为十六进制字符串
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    //生成随机字符串
    private static String createNonceStr() {
        return UUID.randomUUID().toString();
    }

    //生成时间戳
    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
